package com.yicong.ants.ui.present;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Html;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.databinding.DataBindingUtil;

import com.binioter.guideview.GuideBuilder;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.PrefHelper;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.google.gson.Gson;
import com.yicong.ants.BuildConfig;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.account.UserBean;
import com.yicong.ants.bean.ad.AntsAd;
import com.yicong.ants.bean.task.TaskInfo;
import com.yicong.ants.databinding.TaskCenterActivityBinding;
import com.yicong.ants.databinding.TaskListItemBinding;
import com.yicong.ants.databinding.ViewInProgressBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.RouterHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.ad.AdManager;
import com.yicong.ants.manager.ad.AntsAdHelper;
import com.yicong.ants.manager.ad.EventHelper;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.ui.me.UserInfoActivity;
import com.yicong.ants.ui.scenic.ScenicTabActivity;
import com.yicong.ants.ui.video.RewardVideoActivity;
import com.yicong.ants.utils.AppUtils2;
import com.yicong.ants.utils.GroupLayoutHelp;
import com.yicong.ants.utils.GuideHelper;
import com.yicong.ants.utils.SPUtils;
import com.yicong.ants.utils.TimeHelper;
import com.yicong.ants.view.component.TaskCenterGuideComponent2;
import com.yicong.ants.view.component.TaskCenterGuideComponent3;
import com.zx.sdk.ZxSDK;
import com.zx.sdk.util.ConfigHelper;
import com.zx.sdk.util.LogHelper;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 任务中心
 *
 * @author cch
 * @version 2020/8/22
 */
public class TaskCenterActivity extends BaseTitleBarActivity<TaskCenterActivityBinding> implements View.OnClickListener {
    public static final String KEY_TASK_FINISH_DATE = "TASK_FINISH_DATE";
    TaskInfo mBean = new TaskInfo();
    TaskInfo ycBean = new TaskInfo();
    boolean mRealCheck;
    View startAdBtn = null;

    private GroupLayoutHelp layoutHelp;

    @Override
    protected int getLayout() {
        return R.layout.task_center_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleBarVisible(false);
        AppHelper.transStatus(getWindow());
        BarUtils.setStatusBarLightMode(this, false);
        mDataBind.setClick(this);
        mDataBind.setBean(mBean);
        if (!UserManager.getUserBean().getIsAuth()) {
            UiHelper.showConfirmDialog(mContext, "观看提示", "您还没有实名认证，无法开启任务，是否前往认证？", (dialog, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    Router.turnTo(mContext, UserInfoActivity.class).start();
                }
                finish();
            });
        } else {
            onLoadData();
        }

        layoutHelp = new GroupLayoutHelp(mDataBind.groupLayout)
                .setOnSelectClickListener(position -> {
                    if (position == 1) {
                        updatePage2();
                    } else if (position == 2) {
                        updatePage1();
                    }
                }).ok();

        mDataBind.headerFl.getBackground().setAlpha(0);
        mDataBind.contentSv.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            float alp = scrollY * 0.02f;
            if (alp < 0) {
                alp = 0;
            } else if (alp > 1) {
                alp = 1;
            }
            mDataBind.headerFl.getBackground().setAlpha((int) (255 * alp));
        });
        if ("1".equals(ZzConfigs.getClientConf().getAd_task_switch())) {
            startAdBtn = mDataBind.startAd;
            mDataBind.startAd.setEnabled(true);
            mDataBind.taskLook.setVisibility(View.INVISIBLE);
        } else {
            startAdBtn = mDataBind.taskLook;
            mDataBind.startAd.setEnabled(false);
            mDataBind.taskLook.setVisibility(View.VISIBLE);
        }
    }

    void checkGuideExchange() {
        if (!UserManager.getUserBean().getIsAuth()) {
            return;
        }

        if (UserManager.getUserBean().getCoin_float() != 10) {
            return;
        }

        if (CollectionHelper.isNotEmpty(mBean.getTask_ing())) {
            return;
        }

        View anchor = mDataBind.content.getChildAt(0);
        if (anchor == null) {
            return;
        }

        if (!PrefHelper.isFirstTimes(Constants.Prefs.task_step2)) {
            return;
        }

        anchor.findViewById(R.id.exchange_task).post(() -> {
            TaskCenterGuideComponent2 component = new TaskCenterGuideComponent2();
            GuideHelper.showTaskGuideView(thisActivity, anchor.findViewById(R.id.exchange_task), component, new GuideBuilder.OnVisibilityChangedListener() {
                @Override
                public void onShown() {

                }

                @Override
                public void onDismiss() {
                    mDataBind.taskLook.post(() -> {
                        TaskCenterGuideComponent3 component = new TaskCenterGuideComponent3();
                        GuideHelper.showTaskGuideView(thisActivity, mDataBind.taskLook, component, new GuideBuilder.OnVisibilityChangedListener() {
                            @Override
                            public void onShown() {
                            }

                            @Override
                            public void onDismiss() {
                            }
                        });
                    });
                }
            });
        });
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Ants_Ad_Complete:
                onAdFullPlayComplete(event.getBean());
                AntsAdHelper.clearAdInfo(AntsAdHelper.Position.ant_daily_task);
                break;
            case Constants.Event.Real_Check_Suc:
                mRealCheck = true;
                showToast("验证成功，正在加载广告资源");
                RxHelper.timerConsumer(300, aLong -> startAdBtn.performClick());
                break;
            case Constants.Event.Auth_Suc:
                onLoadData();
                break;
            case Constants.Event.NO_AD_FINAL:
                loadTaskTarget2();
                break;
        }
    }

    private void onAdFullPlayComplete(Object object) {
        if (object == null) {
            UiHelper.showToast("完成广告奖励数据异常，请稍候再试");
            return;
        }

        if (!(object instanceof Map)) {
            UiHelper.showToast("完成广告奖励数据异常，请稍候再试1");
            return;
        }
        addSubscribe(RetrofitHelper.getApis().adVideoComplete((Map<String, Object>) object)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if ("2001".equals(respBean.getCode())) {
                        LogHelper.d("今日看广告任务已经完成");
                        EventHelper.reportEvent("task_complete");
                        Dialogs.showTaskSucNew(mContext, respBean.getData().getTotal_coin(), respBean.getData().getTotal_yc());
                        onLoadData();
                        RxBus.get().postEvent(Constants.Event.Expect_Refresh_Dashboard);
                        return;
                    }
                    if (respBean.isCodeFail()) {
                        UiHelper.showConfirmDialog(mContext, respBean.getMsg(), null);
                    } else {
                        UiHelper.showLongToast(respBean.getMsg());
                    }
                    onLoadData();
                }, RxHelper.getHideProgressConsumer(this)));
    }

    private void updateAdStep() {
        mDataBind.taskStatus.setText("（" + mBean.getToday_task_times() + "/" + mBean.getNeed_task_times() + "）");
        mDataBind.taskProgress.setCurrent(mBean.getToday_task_times(), mBean.getNeed_task_times());
        if (mBean.is_complete_task()) {
            mDataBind.taskStatus.setText("（已完成）");
            mDataBind.taskLook.setText("继续观看");
            mDataBind.taskStatus.setTextColor(UiHelper.getColor(R.color.themeColor));
            SPUtils.put(mContext, KEY_TASK_FINISH_DATE + UserManager.getUserId(), System.currentTimeMillis());
        }
    }

    void realCheck() {
        showProgress();
        addSubscribe(RetrofitHelper.getApis().realCheck(Collections.emptyMap())
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();

                    mRealCheck = respBean.isCodeSuc();
                    if (mRealCheck) {
                        startAdBtn.performClick();
                    }
                }, RxHelper.getHideProgressConsumer(this)));
    }

    @Override
    protected void onLoadData() {
        showProgress();
        addSubscribe(RetrofitHelper.getApis().taskInfo()
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        return;
                    }
                    if (ConfigHelper.getShowInterstitialPages().contains("task")) {
                        AdManager.showInterstitial(this);
                    }
                    mBean = respBean.getData();
                    getYCBean();
                }, RxHelper.getHideProgressConsumer(this)));

    }

    private void getYCBean() {
        addSubscribe(RetrofitHelper.getApis().ycTaskInfo()
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        return;
                    }
                    ycBean = respBean.getData();
                    mDataBind.setBean(mBean);
                    mDataBind.setYcBean(mBean);
                    updateInfo();
                }, RxHelper.getHideProgressConsumer(this)));
    }

    private void updateInfo() {
        if (layoutHelp.getSelected() == 1) {
            updatePage2();
        } else {
            updatePage1();
        }
        updateAdStep();
        mDataBind.taskRuleContent.setText(Html.fromHtml(mBean.getTask_rule()));
        mDataBind.needWatchCountTv.setText("每日0:00更新奖励任务；每日完整观看 " + mBean.getNeed_task_times() + "个广告视频完成每日奖励任务");
        UiHelper.setVisibleElseGone(mDataBind.taskRule, false);
        mDataBind.content.post(() -> {
            RxHelper.timerConsumer(200, aLong -> {
                checkGuideExchange();
            });
        });
    }

    void fetchTask(TaskInfo.ListBean itemBean) {
        showProgress();
        Map<String, String> map = new HashMap<>();
        map.put("task_id", String.valueOf(itemBean.getTask_id()));
        addSubscribe(RetrofitHelper.getApis().fetchTask(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeSuc()) {
                        Dialogs.showGetTaskSuc(mContext, this::onLoadData);
                        RxBus.get().postEvent(Constants.Event.Expect_Refresh_Dashboard);
                        return;
                    }
                    showToast(respBean.getMsg());
                }, RxHelper.getHideProgressConsumer(TaskCenterActivity.this)));
    }

    void fetchYCTask(TaskInfo.ListBean itemBean) {
        showProgress();
        Map<String, String> map = new HashMap<>();
        map.put("task_id", String.valueOf(itemBean.getTask_id()));
        addSubscribe(RetrofitHelper.getApis().fetchYCTask(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeSuc()) {
                        Dialogs.showGetTaskSuc(mContext, this::onLoadData);
                        RxBus.get().postEvent(Constants.Event.Expect_Refresh_Dashboard);
                        return;
                    }
                    showToast(respBean.getMsg());
                }, RxHelper.getHideProgressConsumer(TaskCenterActivity.this)));
    }

    void updatePage1() {
        mDataBind.content.removeAllViews();
        List<TaskInfo.ListBean> list = mBean.getTask_list();
        //添加进行中任务
        ViewGroup parent = mDataBind.content;
        ViewInProgressBinding viewInProgressBinding = DataBindingUtil.inflate(mLayoutInflater, R.layout.view_in_progress, parent, false);
        viewInProgressBinding.goToProgress.setTag(1);
        viewInProgressBinding.setClick(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(49));
        parent.addView(viewInProgressBinding.getRoot(), layoutParams);

        for (int i = 0; i < list.size(); i++) {
            TaskInfo.ListBean itemBean = list.get(i);
            layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            if (itemBean.getType() == 2) {
                layoutParams.topMargin = ConvertUtils.dp2px(4);
            }
            TaskListItemBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.task_list_item, parent, false);
            binding.setUnit("门票");
            binding.setDay("天");
            binding.setBean(list.get(i));
            binding.setClick(v -> {
                if (!UserManager.getUserBean().getIsAuth()) {
                    showToast("您还没有完成实人认证");
                    Router.turnTo(mContext, UserInfoActivity.class).start();
                    return;
                }

                UiHelper.showCancelDialog(mContext, ZzConfigs.getClientConf().getTask_fetch_tip()
                        , Pair.create("确定", (dialog, which) -> {
                            //
                            fetchTask(itemBean);
                        }), Pair.create("取消", null));
            });
            parent.addView(binding.getRoot(), layoutParams);
        }
        mDataBind.exchangeCenterLl.setVisibility(View.VISIBLE);
    }

    @SuppressLint("SetTextI18n")
    void updatePage2() {
        mDataBind.content.removeAllViews();
        //添加进行中任务
        ViewGroup parent = mDataBind.content;
        ViewInProgressBinding viewInProgressBinding = DataBindingUtil.inflate(mLayoutInflater, R.layout.view_in_progress, parent, false);
        viewInProgressBinding.goToProgress.setTag(2);
        viewInProgressBinding.setClick(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(49));
        parent.addView(viewInProgressBinding.getRoot(), layoutParams);

        List<TaskInfo.ListBean> list = ycBean.getTask_list();
        for (int i = 0; i < list.size(); i++) {
            //status 1可以兑换
            TaskInfo.ListBean itemBean = list.get(i);
            layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            if (itemBean.getType() == 2) {
                layoutParams.topMargin = ConvertUtils.dp2px(4);
            }
            TaskListItemBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.task_list_item, parent, false);
            binding.setUnit("yc");
            binding.setStatus("2");
            binding.setDay("天");

            if (itemBean.isIs_limit()) {
                binding.tvMargin.setText("剩余：" + itemBean.getStock());
            } else {
                binding.tvMargin.setText("");
            }

            if (itemBean.getStatus() != 1) {
                if (itemBean.getTask_id() == 1) {
                    binding.exchangeTask.setVisibility(View.VISIBLE);
                } else {
                    binding.exchangeTask.setBackgroundResource(R.drawable.new_btn_bg_grey);
                    binding.exchangeTask.setTextColor(ContextCompat.getColor(this, R.color.new_text_color_3));
                    binding.exchangeTask.setEnabled(false);
                    binding.exchangeTask.setClickable(false);
                }
            }
            binding.setBean(list.get(i));
            binding.setClick(v -> {
                if (!UserManager.getUserBean().getIsAuth()) {
                    showToast("您还没有完成实人认证");
                    Router.turnTo(mContext, UserInfoActivity.class).start();
                    return;
                }

                UiHelper.showCancelDialog(mContext, ZzConfigs.getClientConf().getTask_fetch_tip().replaceAll("门票", "yc")
                        , Pair.create("确定", (dialog, which) -> {
                            //
                            fetchYCTask(itemBean);
                        }), Pair.create("取消", null));
            });
            parent.addView(binding.getRoot(), layoutParams);
        }
        mDataBind.exchangeCenterLl.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            mDataBind.startAd.randomLayout();
        } catch (Exception ignored) {
        }
        preloadRewardIfTaskNotFinish();
    }

    // 加载第四个跳转链接
    private void loadTaskTarget() {
        showProgress();
        addSubscribe(RetrofitHelper.getApis().dailyTaskTarget(Collections.emptyMap())
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        return;
                    }

                    // 小于等于0 就播放激励视频
                    if (respBean.getData().getAd_id() <= 0) {
                        AdManager.showReward(thisActivity, Constants.Event.Ants_Ad_Complete);
                        return;
                    }

                    AntsAd adInfo = respBean.getData();
                    AntsAdHelper.setAdInfo(adInfo, AntsAdHelper.Position.ant_daily_task);
                    if ("video".equals(adInfo.getDisplay_type())) {
                        Router.turnTo(mContext, RewardVideoActivity.class).start();
                        return;
                    }
                    RouterHelper.tryRoutePlatformUri(thisActivity, adInfo.getDisplay());
                }, RxHelper.getHideProgressConsumer(this)));
    }

    // 加载第四个跳转链接
    private void loadTaskTarget2() {
        showProgress();
        addSubscribe(RetrofitHelper.getApis().dailyTaskTarget2(Collections.emptyMap())
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        return;
                    }
                    // 小于等于0 就播放激励视频
                    if (respBean.getData().getAd_id() > 0) {
                        AntsAd adInfo = respBean.getData();
                        AntsAdHelper.setAdInfo(adInfo, AntsAdHelper.Position.ant_daily_task);
                        if ("video".equals(adInfo.getDisplay_type())) {
                            Router.turnTo(mContext, RewardVideoActivity.class).start();
                            return;
                        }
                        RouterHelper.tryRoutePlatformUri(thisActivity, adInfo.getDisplay());
                    }
                }, RxHelper.getHideProgressConsumer(this)));
        reportError();
    }

    private void reportError() {
        String date = TimeUtils.millis2String(System.currentTimeMillis(), "yyyy-MM-dd");
        String dateSS = TimeUtils.millis2String(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
        String key = "KEY_ADV_ERROR_" + date;
        int errorCount = com.blankj.utilcode.util.SPUtils.getInstance().getInt(key, 0);
        if (errorCount == 0) {
            com.blankj.utilcode.util.SPUtils.getInstance().put("KEY_ADV_ERROR_DATE", dateSS);
        } else {
            dateSS = com.blankj.utilcode.util.SPUtils.getInstance().getString("KEY_ADV_ERROR_DATE", "");
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("source", "ant");
        params.put("appCode", "ant");
        params.put("versionCode", BuildConfig.VERSION_CODE + "");
        params.put("platform", "1");
        params.put("versionName", BuildConfig.VERSION_NAME);
        params.put("lastPhoneBrand", Build.BRAND);
        params.put("lastEquipmentName", Build.MODEL);
        params.put("errorCount", ++errorCount + "");
        com.blankj.utilcode.util.SPUtils.getInstance().put(key, errorCount);
        params.put("cacheTime", dateSS);
        UserBean userBean = UserManager.getUserBean();
        if (userBean != null) {
            params.put("userId", userBean.getId());
            params.put("mobile", userBean.getMobile());
            params.put("userCreateTime", userBean.getCreate_time());
            params.put("niceNumber", userBean.getNice_number());
            params.put("avatar", userBean.getAvatar());

        }
        addSubscribe(RetrofitHelper.getApis().reportAdvError(ZxSDK.BASE_API_URL + "/api/client/error", params)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                }, RxHelper.getHideProgressConsumer(this)));

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_ad:
            case R.id.task_look:
                if (mBean == null) {
                    onLoadData();
                    return;
                }
                if (!mBean.isIs_yc_task() && (mBean.getTask_ing() == null || mBean.getTask_ing().size() == 0)) {
                    UiHelper.showConfirmDialog(mContext, "您还没有兑换奖励", null);
                    return;
                }

                // 第4个视频，id=1 表示播放视频
                if (mBean.getToday_task_times() == 3) {
                    loadTaskTarget();
                    return;
                }

                // 滑动验证码
                if (!mRealCheck && mBean.getToday_task_times() == 4) {
                    realCheck();
                    return;
                }

                Dialogs.showTaskDisclaimer(thisActivity, () -> {
                    //
                    EventHelper.reportEvent("task_center_start_ad");
                    if (mBean.is_complete_task()) {
                        AdManager.preloadAndShowReward(thisActivity, Constants.Event.Ants_Ad_Complete);
                        return;
                    }
                    AdManager.showReward(thisActivity, Constants.Event.Ants_Ad_Complete);
                });

                break;
            case R.id.back:
                onBackPressed();
                break;
            case R.id.task_rule:
                boolean isVisible = UiHelper.isVisible(mDataBind.taskRuleContent);
                Drawable drawable = getResources().getDrawable(!isVisible ? R.drawable.task_sign_up : R.drawable.task_sign_down);
                mDataBind.taskRule.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
                UiHelper.setVisibleElseGone(mDataBind.taskRuleContent, !UiHelper.isVisible(mDataBind.taskRuleContent));
                break;
            case R.id.scenicBtn:
                Router.turnTo(this, ScenicTabActivity.class).start();
                break;
            case R.id.hotelBtn:
                ZzConfigs.toWebActivityByUrl(this, "hotel");
                break;
            case R.id.mallBtn:
                ZzConfigs.toWebActivityByUrl(this, "mall");
                break;
            case R.id.goToProgress:
                if ((int) v.getTag() == 1) {
                    Router.turnTo(mContext, DoingTaskActivity.class).putExtra("TaskInfo", new Gson().toJson(mBean)).start();
                } else {
                    Router.turnTo(mContext, DoingYCTaskActivity.class).putExtra("TaskInfo", new Gson().toJson(ycBean)).start();
                }
                break;
        }
    }

    private void preloadRewardIfTaskNotFinish() {
        Long finishDate = (Long) SPUtils.get(mContext, KEY_TASK_FINISH_DATE + UserManager.getUserId(), 0L);
        if (!TimeHelper.isSameDay(System.currentTimeMillis(), finishDate)) {//如果今天未完成
            AdManager.preloadRewardOnly(thisActivity, Constants.Event.Ants_Ad_Complete);
        }
    }

    @Override
    protected void onDestroy() {
        ZxSDK.destroyReward(this, false);
        super.onDestroy();
    }

    //160

    //420 *** 411（2.625）

    //320 720   (411 720 -> 2.252 *160 -> 360.32)

    //540 1080 320dp（3.375） -> 420 1080 411（2.625）

    //411 1080 （B/A+0.5）= 2.625 * 160 -> 420
    @Override
    protected void attachBaseContext(Context base) {
        Configuration config = base.getResources().getConfiguration();
        config.fontScale = 1f;
        config.densityDpi = (int) ((UiHelper.getScreenWidth() / 411 + 0.5) * 160);
        Context context = base.createConfigurationContext(config);
        super.attachBaseContext(Objects.requireNonNull(new AppUtils2().attachBaseContext(context)));
    }
}
